package vrp;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import java.io.IOException;
import javax.jdo.PersistenceManager;
import javax.servlet.http.*;

import vrp.PMF;
import vrp.Delivery;
import vrp.SaleOrder;
import vrp.Product;

public class DeliveryReenableServlet extends HttpServlet {

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {

    	PersistenceManager pm = PMF.get().getPersistenceManager();
    	
    	long deliveryID = Integer.parseInt(req.getParameter("delivery"));
        Key deliveryKey = KeyFactory.createKey(Delivery.class.getSimpleName(), deliveryID);
        Delivery delivery = pm.getObjectById(Delivery.class, deliveryKey);

        String urlSaleOrder = req.getParameter("urlSaleOrder");
        String respondRedirect = "/deliveries.jsp?";
        if (!urlSaleOrder.equals("null")) {
            Key saleOrderKey = delivery.getSaleOrder();
            SaleOrder saleOrder = pm.getObjectById(SaleOrder.class, saleOrderKey);
            respondRedirect += "saleOrder="+saleOrder.getKey().getId()+"&";
        }

        try {
            Key productKey = delivery.getProduct();
            Product product = pm.getObjectById(Product.class, productKey);
            int inventory = product.getInventory();
            int quantity = delivery.getQuantity();
            
            if (inventory < quantity) {
            	pm.close();
            	resp.sendRedirect(respondRedirect + "error=inventory&");
            	return;
            }

            product.setInventory(inventory-quantity);
            pm.makePersistent(product);
            
            delivery.setStatus(0); //PROCESSING
            pm.makePersistent(delivery);
        } finally {
            pm.close();
        }
        resp.sendRedirect(respondRedirect);
    }
}